<template>
  <div class="relationship-wrapper">
    <div class="head">
      <div class="title">亲友关系</div>
      <div class="btns">
        <div class="add-btn" @click="addRelationship">
          <span>添加亲友关系</span>
        </div>
        <div class="tabs-switch">
          <div :class="{'active': showView === 'view'}" @click="handleClickTab('view')">
            <el-icon><Picture /></el-icon>
          </div>
          <div :class="{'active': showView === 'list'}" @click="handleClickTab('list')">
            <el-icon><operation /></el-icon>
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <!-- 视图 -->
      <div class="view-img" v-show="showView === 'view'">
        <template v-if="data.length>0">
          <div class="main-avatar">
            <div class="avatar-info">
              <el-avatar v-if="self?.gender === '男'" class="avatar-img" :src="male"></el-avatar>
              <el-avatar v-if="self?.gender === '女'" class="avatar-img" :src="female"></el-avatar>
              <span class="name">{{self?.name}}</span>
              
            </div>
            
          </div>
          <div class="accessory-avatar">
            <div class="avatar-info" v-for="item in data" :key="item.id">
              <div class="image">
                <el-avatar v-if="item.customerSex === '男'" class="avatar-img" :src="male"></el-avatar>
                <el-avatar v-if="item.customerSex === '女'" class="avatar-img" :src="female"></el-avatar>
              </div>
              
              <span class="name">{{item.customerName}}</span>
              <div class="labels">
                <span class="label-item" v-for="t in item.associatedNameShow">{{t}}</span>
              </div>
              
            </div>
          </div>
        </template>
        <template v-else>
          <el-empty description="暂未添加亲友关系"></el-empty>
        </template>
      </div>
      <!-- 表格 -->
      <div class="view-table" v-show="showView === 'list'">
        <ztable 
            :tableData='data' 
            :strucs='Column'
            @onToDetail="onToDetail"
            :isshowOperation="true"
          >
          <template #default="slotScope">
            <el-button type="text" class="operation" @click="handleEdit(slotScope.rowData)">编辑</el-button>
            <el-button type="text" class="operation" @click="handleDelete(slotScope.rowData, slotScope.index)">删除</el-button>
          </template>
          </ztable>
      </div>
    </div>
  </div>

  <!-- 新建、编辑亲友关系 -->
      <zdialog @handleClose="close" v-model="dialogVisible" :btnData="btnData" :title="title">
        <template #body>
          <div class="wrapper">
            <div class="leftToRight-layout">
                <div class="label">
                  <span>添加亲友</span>
                </div>
                <div class="operations">
                  <zsearchname @setName="setName" :personName="personName"></zsearchname>
                </div>
            </div>
            <div class="person-info">
              <customInfo :data="personInfo" v-show="isNotData"></customInfo>
              <el-empty description="暂无数据" v-show="!isNotData"></el-empty>
            </div>
            <div class="leftToRight-layout">
              <div class="label">
                <span>亲友关系</span>
              </div>
              <div class="operations">
                <el-select multiple v-model="associatedNameShow"  placeholder="请选择">
                  <el-option
                    v-for="item in relationshipList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
        </template>
      </zdialog>
</template>

<script lang="ts">
import { Operation, Picture } from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, PropType, watch } from 'vue';
// 引入图片资源
import male from "./../../../../assets/image/male-adult.png"
import female from "./../../../../assets/image/female-adult.png"

import zdialog from '@components/dialog/dialog.vue'
import ztable from '@components/Table/index.vue'
import zsearchname from "../../../../components/searchinput/searchName.vue"
import useRequest from "../../../../hook/request"
import { Option } from "../../../../types/index"
import customInfo from "../../../../components/customInfo/customInfo.vue"
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

import useSetAddLog from "../../../../hook/setAddLog"

type DataList = {
  id: number,
  customerSex: string,
  associatedNameShow: string[],
  customerName: string

}

type SelfType = {
      name: string,
      gender: string
    }
export default defineComponent({
  name: 'Relationship',
  components: {
    zdialog,
    ztable,
    zsearchname,
    customInfo,

    Operation, Picture
  },
  props: {
    self: {
      type: Object as PropType<SelfType>
    }
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    let id = route.params.id

    watch(() => route.params.id, (newID) => {
      if(newID) {
        id = newID
        getList()
      }
      
    })
    const state = reactive({
      data: <DataList[]>[],
      Column: [
        {
          id: 529,
            name: "associatedName",
            viewName: "关系",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "customerName",
            viewName: "亲友",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "customerHistorySickNum",
            viewName: "病历号",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "customerSex",
            viewName: "性别",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "customerPhone",
            viewName: "手机",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
      ],
      dialogVisible: false,
      relationshipList: <Option[]>[],
      associatedName: '',
      personInfo: <any>{},
      isNotData: false,
      associatedCustomerId: null,
      associatedNameShow: <string[]>[],
      showView: 'view',
      isAvatarShow: false,
      title: '新建亲友关系',
      personName: '',
    })

    const btnData = [
      {
        name: '取消',
        func: () => {
          close()
        }
      },
      {
        name: '确定',
        func: () => {
          if(state.associatedNameShow.length > 0) {
            if(state.title === '新建亲友关系') {
              addSave()
            }

            if(state.title === '编辑亲友关系') {
              eidtSave()
            }
            
          } else {
            ElMessage.warning('请选择亲友关系')
            return false
          }
        }
      }
    ]

    const addRelationship = () => {
      state.dialogVisible = true;
      state.title = '新建亲友关系'
    }

    const close = () => {
      state.dialogVisible = false;
      state.associatedCustomerId = null
      state.personInfo = {}
      state.associatedNameShow = []
      state.isNotData = false
      state.personName = ''

    }

    const setName = (data: any) => {
      if(Object.keys(data).length > 0) {
        state.personInfo = data
        state.associatedCustomerId = data.id
        state.isNotData = true
      } else {
        state.isNotData = true
      }
      
    }
    const getrelationshipList = async() => {
      let result: any = await useRequest('customer/info/getCustomerAssociatedNameSelect', {}, 'GET')
      console.log(result.data)
      state.relationshipList = result.data || []
    }
    getrelationshipList()

    const addSave = async() => {
      let result: any = await useRequest('customer/info/addAssociatedCustomer', {
        customerId: id,
        associatedCustomerId: state.associatedCustomerId,
        associatedNameShow: state.associatedNameShow
      }, 'POST')

      if(result.code != 0) {
        ElMessage.error(result.msg)
        return false
      }
      ElMessage.success('添加亲友' + result.msg)
      close()
      getList()

      console.log(result.data)
    }

    const eidtSave = async() => {
      let result: any = await useRequest('customer/info/updateAssociated', {
        id: state.associatedCustomerId,
        associatedNameShow: state.associatedNameShow
      }, 'POST')
      if(result.code != 0) {
        ElMessage.error(result.msg)
        return false
      }
      ElMessage.success('编辑亲友' + result.msg)
      close()
      getList()
    }

    const getList = async() => {
      let result: any = await useRequest(`customer/info/getAssociatedCustomerList/${id}`, {}, 'GET')
      console.log(result.data)
      state.data = result.data || []
    }

    getList()

    const handleClickTab = (type: string) => {
      state.showView = type
    }

    const onToDetail = (id: number) => {
      console.log(id)
      useSetAddLog(id)
      router.push(`/allPatientDetails/${id}/patient`)
      
    }

    const handleEdit = (data:any) => {
      console.log('编辑', data)
      state.dialogVisible = true;
      state.title = '编辑亲友关系';
      state.associatedNameShow = data.associatedNameShow;
      state.associatedCustomerId = data.id
      state.personName = data.customerName
      state.isNotData = true
      state.personInfo = data.customerInfo

    }

    const handleDelete = (data: any, index: number) => {
      let id = data.id
      ElMessageBox.confirm('此操作将删除亲友关系, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
				let result: any = await useRequest(`customer/info/delAssociated/${id}`, {}, 'POST')
        if(result.code != 0) {
          ElMessage.error(result.msg)
          return false
        }
        ElMessage.success('删除' + result.msg)
        getList()
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      
    }
    return {
      male,
      female,
      ...toRefs(state),
      btnData,
      addRelationship,
      close,
      setName,
      handleClickTab,
      onToDetail,
      handleEdit,
      handleDelete
    }
  }
})
</script>

<style lang="scss" scoped>
.relationship-wrapper {
  box-shadow: 0 2px 8px #ececec;
  width: 100%;
  font-size: 14px;

  .head {
    display: flex;
    height: 50px;
    line-height: 50px;
    width: 100%;

    .title {
      padding-left: 30px;
      font-weight: bold;
      flex: 1;
    }

    .btns {
      text-align: right;
      display: flex;
      padding-right: 20px;

      .add-btn {
        & > span {
          padding: 5px;
          border-radius: 4px;
          background-color: $mainColor;
          color: #fff;
          cursor: pointer;
        }
      }

      .tabs-switch {
        display: flex;
        align-items: center;
        justify-content: center;

        & > div {
          width: 40px;
          height: 30px;
          line-height: 30px;
          background: #fff;
          text-align: center;
          border: 1px solid #ccc;
          margin: 0 5px;
          cursor: pointer;
          
          & > i {
            font-size: 16px;
          }
        }
        & > div:nth-child(1) {
          margin-right: 0;
          border-right: 0;
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
        & > div:nth-child(2) {
          margin-left: 0;
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }

        .active {
          background-color: $mainColor;
        }
      }
    }
  }

  .content {
    height: 280px;

    .view-img {
      height: 100%;
      display: flex;
      flex-direction: column;

      .main-avatar {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        .avatar-info {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 40px;
          
          .avatar-img {
            width: 60px;
            height: 60px;
            cursor: pointer;
          }
          .name {
            padding-left: 10px;
          }

        }
        
      }

      .accessory-avatar {
        flex: 1;
        display: flex;
        justify-content: center;
        .avatar-info {
          display: flex;
          flex-direction: column;
          margin: 0 20px;
          
          .image {
            text-align: center;
          }
          .avatar-img {
            width: 40px;
            height: 40px;
            cursor: pointer;
          }
          .name {
            padding-top: 10px;
            text-align: center;
          }

          .labels {
            display: flex;

            .label-item {
              background-color: $mainColor;
              color: #fff;
              text-align: center;
              margin: 2px 5px;
              padding: 2px 3px;
              border-radius: 4px;
              font-size: 12px;
            }
          }
          

        }
      }
    }
  }
}


</style>